package easy;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import util.PrintUtils;

public class Solution_1356 {

    public int[] sortByBits(int[] arr) {
        Arrays.sort(arr);
        List<Integer>[] counts = new List[10001];
        for (int num : arr) {
            int c = num, count = Integer.bitCount(num);

            /*while (c > 0) {
                int mod = c % 2;
                count += mod;
                c >>= 1;
            }*/
            List<Integer> list = counts[count];
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(num);
            counts[count] = list;
        }

        int[] res = new int[arr.length];
        for (int i = 0, index = 0; i < counts.length; i++) {
            if (counts[i] != null) {
                for (Integer integer : counts[i]) {
                    res[index++] = integer;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Solution_1356 model = new Solution_1356();
        PrintUtils.arrayInt(model.sortByBits(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8}));
        PrintUtils.arrayInt(model.sortByBits(new int[]{1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1}));
        PrintUtils.arrayInt(model.sortByBits(new int[]{10000, 10000}));
        PrintUtils.arrayInt(model.sortByBits(new int[]{2, 3, 5, 7, 11, 13, 17, 19}));
        PrintUtils.arrayInt(model.sortByBits(new int[]{10, 100, 1000, 10000}));
        PrintUtils.arrayInt(model.sortByBits(new int[]{10, 100, 0, 10000}));
    }
}
